package com.lingxu.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @Title: StartConfig
 * @Package: com.lingxu.config
 * @Author: ysj闫世杰
 * @Email: 1105324813@qq.com
 * @Date: Created in 2023/11/13 16:49
 * @Description:
 * @Version: 1.0.0
 */
@Component
@Slf4j
public class StartConfig {

    public static void run(){

        try {
            boolean exist = findPort();
            //已启动则不执行
            //没有启动
            if(!exist){
                String path = Thread.currentThread().getContextClassLoader().getResource("dim/dimenmodel-1.0.1.jar").getPath();
                path = path.substring(1);
                String cmd = "java -javaagent:" + path + " -jar " + path;
                log.info("启动建模平台。。。。。。。。。。。。。。。。");
                Process process = Runtime.getRuntime().exec(cmd);
                InputStream is = process.getInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String content = br.readLine();
                while (content != null) {
                    System.out.println(content);
                    content = br.readLine();
                }
            }else {
                log.info("建模平台已在启动状态。。。。。。。。。。。。");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static boolean findPort() throws Exception{
        boolean exist = false;
        String findPort = "netstat -ano | findstr \"9999\"";
        Process process = Runtime.getRuntime().exec(findPort);
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String content = br.readLine();
        while (content != null) {
            exist = true;
            System.out.println(content);
            content = br.readLine();
        }
        System.out.println(exist);
        return exist;
    }

    public static void main(String[] args) throws Exception{
        findPort();
    }
}
